<template>
  <div v-if="visible" class="bay-viewer-overlay" @click="handleOverlayClick">
    <div class="bay-viewer-modal" @click.stop>
      <!-- 模态框头部 -->
      <div class="modal-header">
        <div class="header-content">
          <h2 class="modal-title">{{ yardId }} 堆场 - 第 {{ bayNumber }} 贝</h2>
          <div class="bay-info">
            <span class="info-item">排数: {{ rowCount }}</span>
            <span class="info-item">层数: {{ tierCount }}</span>
            <span class="info-item">集装箱数: {{ containerCount }}</span>
          </div>
        </div>
        <button class="close-btn" @click="closeModal" title="关闭">
          <span class="close-icon">×</span>
        </button>
      </div>

      <!-- 模态框内容 -->
      <div class="modal-content">
        <!-- 贝图展示区域 -->
        <div class="bay-view" ref="bayView">
          <!-- 贝图网格 -->
          <div class="bay-grid" ref="bayGrid">
            <!-- 排号标题 -->
            <div class="column-headers">
              <!-- 层号标题 -->
              <div class="tier-header" :style="tierHeaderStyle"></div>
              <div
                  v-for="row in rowCount"
                  :key="row"
                  class="column-header"
                  :class="{ 'empty': !shouldShowRow(row) }"
                  :style="rowHeaderStyle"
              >
                {{ shouldShowRow(row) ? formatRowNumber(row) : '' }}
              </div>
            </div>

            <!-- 层级行 -->
            <div class="bay-row" v-for="tier in reversedTiers" :key="tier">
              <div
                  class="tier-number"
                  :class="{ 'empty': !shouldShowTier(tier) }"
                  :style="tierRowStyle"
              >
                {{ shouldShowTier(tier) ? formatTierNumber(tier) : '' }}
              </div>

              <!-- 单个位置 -->
              <div
                  v-for="row in rowCount"
                  :key="row"
                  class="grid-cell"
                  :class="getCellClass(row, tier)"
                  :style="cellStyle"
                  :data-row="row"
                  :data-tier="tier"
                  @click="onCellClick(row, tier)"
                  @mouseenter="onCellHover(row, tier)"
                  @mouseleave="onCellLeave"
              >
                <!-- 计划覆盖层显示 -->
                <div 
                  v-if="getPlanAtPosition(row, tier)"
                  class="plan-overlay"
                  :style="getPlanOverlayStyle(getPlanAtPosition(row, tier))"
                  :title="getPlanTooltip(getPlanAtPosition(row, tier))"
                >
                </div>
                
                <!-- 加锁覆盖层显示 -->
                <div 
                  v-if="getLockAtPosition(row, tier)"
                  class="lock-overlay"
                  :style="getLockOverlayStyle(getLockAtPosition(row, tier))"
                  :title="getLockTooltip(getLockAtPosition(row, tier))"
                >
                  <!-- 加锁信息显示 -->
                  <div class="lock-info">
                    <div class="lock-id">{{ getLockAtPosition(row, tier).lockId }}</div>
                    <div class="lock-time">{{ formatLockTime(getLockAtPosition(row, tier).lockTime) }}</div>
                    <div class="lock-reason">{{ getLockAtPosition(row, tier).lockReason }}</div>
                  </div>
                  <!-- 锁图标 -->
                  <div class="lock-icon">🔒</div>
                </div>
                
                <!-- 集装箱显示 -->
                <div 
                  v-if="getContainerAtPosition(row, tier)"
                  class="container-item"
                  :class="{ 
                    'container-hovered': hoveredCell.row === row && hoveredCell.tier === tier,
                    'container-selected': selectedCell.row === row && selectedCell.tier === tier
                  }"
                  :style="getContainerItemStyle(getContainerAtPosition(row, tier))"
                  :title="getContainerTooltip(getContainerAtPosition(row, tier))"
                >
                  <div class="container-no">
                    <div class="container-letters">{{ splitContainerNo(getContainerAtPosition(row, tier).containerNo).letters }}</div>
                    <div class="container-numbers">{{ splitContainerNo(getContainerAtPosition(row, tier).containerNo).numbers }}</div>
                  </div>
                  <div class="container-type">{{ getContainerAtPosition(row, tier).containerType || '20GP' }}</div>
                </div>
                
                <!-- X号标记显示 -->
                <div 
                  v-if="shouldShowXMark(row, tier)"
                  class="x-mark"
                  :class="{ 
                    'x-mark-hovered': hoveredCell.row === row && hoveredCell.tier === tier,
                    'x-mark-selected': selectedCell.row === row && selectedCell.tier === tier
                  }"
                  :style="xMarkStyle"
                  :title="`偶数贝${bayNumber - 1}的集装箱占用此位置`"
                >
                  <div class="x-line x-line-1"></div>
                  <div class="x-line x-line-2"></div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 详细信息面板 -->
        <div class="detail-panel">
          <h4>位置详细信息</h4>
          <div class="position-info">
            <div v-if="selectedCell.row && selectedCell.tier" class="info-row">
              <span class="label">位置:</span>
              <span class="value">{{ yardId }}-{{ bayNumber }}贝{{ selectedCell.row }}排{{ selectedCell.tier }}层</span>
            </div>
            <div v-else class="info-row">
              <span class="label">贝信息:</span>
              <span class="value">{{ yardId }}-{{ bayNumber }}贝</span>
            </div>
            <div v-if="getDetailContainer(selectedCell.row, selectedCell.tier)" class="container-detail-item">
              <div class="detail-header">
                <span class="tier-badge">第 {{ selectedCell.tier }} 层</span>
                <span class="container-no">{{ getDetailContainer(selectedCell.row, selectedCell.tier).containerNo }}</span>
              </div>
              <div class="detail-info">
                <div class="info-row">
                  <span class="label">集装箱号:</span>
                  <span class="value">{{ getDetailContainer(selectedCell.row, selectedCell.tier).containerNo }}</span>
                </div>
                <div class="info-row">
                  <span class="label">类型:</span>
                  <span class="value">{{ getDetailContainer(selectedCell.row, selectedCell.tier).containerType || '20GP' }}</span>
                </div>
                <div class="info-row">
                  <span class="label">状态:</span>
                  <span class="value">{{ getDetailContainer(selectedCell.row, selectedCell.tier).status || '正常' }}</span>
                </div>
                <div class="info-row">
                  <span class="label">重量:</span>
                  <span class="value">{{ getDetailContainer(selectedCell.row, selectedCell.tier).weight || '未知' }} kg</span>
                </div>
                <div class="info-row">
                  <span class="label">实际位置:</span>
                  <span class="value">{{ yardId }}-{{ getDetailContainer(selectedCell.row, selectedCell.tier).bay }}贝{{ selectedCell.row }}排{{ selectedCell.tier }}层</span>
                </div>
                <div class="info-row">
                  <span class="label">显示位置:</span>
                  <span class="value">{{ yardId }}-{{ bayNumber }}贝{{ selectedCell.row }}排{{ selectedCell.tier }}层</span>
                </div>
              </div>
            </div>
            <div v-else class="empty-position">
              <div class="empty-info">
                <span class="empty-icon">📦</span>
                <span class="empty-text">{{ selectedCell.row && selectedCell.tier ? '该位置无集装箱' : '请点击选择位置查看详细信息' }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 模态框底部 -->
      <div class="modal-footer">
        <!-- 左侧：贝号导航按钮 -->
        <div class="bay-navigation">
          <button 
            class="btn btn-nav btn-prev" 
            @click="goToPreviousBay"
            :disabled="!canGoToPreviousBay"
            title="上一贝"
          >
            <span class="nav-icon">‹</span>
            <span class="nav-text">上一贝</span>
          </button>
          <button 
            class="btn btn-nav btn-next" 
            @click="goToNextBay"
            :disabled="!canGoToNextBay"
            title="下一贝"
          >
            <span class="nav-text">下一贝</span>
            <span class="nav-icon">›</span>
          </button>
        </div>
        
        <!-- 右侧：操作按钮 -->
        <div class="footer-actions">
          <button class="btn btn-secondary" @click="closeModal">关闭</button>
          <button class="btn btn-primary" @click="refreshData">刷新数据</button>
          <button v-if="selectedCell.row && selectedCell.tier" class="btn btn-warning" @click="clearSelection">清除选择</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BayViewer',
  props: {
    // 是否显示模态框
    visible: {
      type: Boolean,
      default: false
    },
    // 堆场ID
    yardId: {
      type: String,
      required: true
    },
    // 贝号
    bayNumber: {
      type: Number,
      required: true
    },
    // 贝数
    bayCount: {
      type: Number,
      required: true
    },
    // 排数
    rowCount: {
      type: Number,
      required: true
    },
    // 层数
    tierCount: {
      type: Number,
      required: true
    },
    // 集装箱数据
    containerData: {
      type: Array,
      required: true
    },
    // 计划数据
    yardPlans: {
      type: Array,
      default: () => []
    },
    // 加锁数据
    yardLocks: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // 当前选中的单元格
      selectedCell: { row: null, tier: null },
      // 当前悬停的单元格
      hoveredCell: { row: null, tier: null },
      // 贝图配置参数（参考YardDetail）
      config: {
        // 基础尺寸
        cellWidth: 100,        // 单元格宽度（像素）
        cellHeight: 100,       // 单元格高度（像素）

        // 标题尺寸（固定常量）
        rowNumberWidth: 40,   // 排号宽度（像素）
        tierNumberHeight: 40, // 层号高度（像素）

        // 显示控制
        intervalDisplayRows: false,  // 是否间隔显示排号
        intervalDisplayTiers: false, // 是否间隔显示层号
      }
    }
  },
  computed: {
    // 当前贝的集装箱数据
    bayContainers() {
      // 先过滤出当前贝的集装箱
      const bayContainers = this.containerData.filter(container => 
        container.bay === this.bayNumber
      )
      
      // 按位置分组，每个位置只保留一个集装箱（取第一个）
      const positionMap = new Map()
      bayContainers.forEach(container => {
        const positionKey = `${container.row}-${container.tier || 1}`
        if (!positionMap.has(positionKey)) {
          positionMap.set(positionKey, container)
        }
      })
      
      return Array.from(positionMap.values())
    },
    // 集装箱总数
    containerCount() {
        // 奇数贝，统计当前贝和相邻两个偶数贝的集装箱
        const prevEvenBay = this.bayNumber - 1  // 前一个偶数贝
        const nextEvenBay = this.bayNumber + 1  // 后一个偶数贝
        
        // 统计当前贝的集装箱
        const currentBayContainers = this.containerData.filter(container => 
          container.bay === this.bayNumber
        )
        
        // 统计前一个偶数贝的集装箱
        const prevEvenContainers = this.containerData.filter(container => 
          container.bay === prevEvenBay
        )
        
        // 统计后一个偶数贝的集装箱
        const nextEvenContainers = this.containerData.filter(container => 
          container.bay === nextEvenBay
        )
        
        // 按位置去重统计
        const positionSet = new Set()
        
        // 添加当前贝的集装箱位置
        currentBayContainers.forEach(container => {
          const positionKey = `${container.row}-${container.tier || 1}`
          positionSet.add(positionKey)
        })
        
        // 添加前一个偶数贝的集装箱位置
        prevEvenContainers.forEach(container => {
          const positionKey = `${container.row}-${container.tier || 1}`
          positionSet.add(positionKey)
        })
        
        // 添加后一个偶数贝的集装箱位置
        nextEvenContainers.forEach(container => {
          const positionKey = `${container.row}-${container.tier || 1}`
          positionSet.add(positionKey)
        })
        
        return positionSet.size
    },
    // 最大层数（使用传入的层数）
    maxTier() {
      return this.tierCount || 1
    },
    // 反转的层号数组，用于从下往上显示
    reversedTiers() {
      const tiers = []
      for (let i = this.maxTier; i >= 1; i--) {
        tiers.push(i)
      }
      return tiers
    },
    // 排号宽度样式计算属性
    rowHeaderStyle() {
      return { 
        height: `${this.config.tierNumberHeight}px`, 
        width: `${this.config.cellWidth}px`
      }
    },
    // 层号高度样式计算属性
    tierHeaderStyle() {
      return { 
        height: `${this.config.tierNumberHeight}px`,
        width: `${this.config.rowNumberWidth}px`
      }
    },
    // 层号行样式计算属性
    tierRowStyle() {
      return { 
        height: `${this.config.cellHeight}px`,
        width: `${this.config.rowNumberWidth}px`
      }
    },
    // 网格单元格样式计算属性
    cellStyle() {
      return {
        width: `${this.config.cellWidth}px`,
        height: `${this.config.cellHeight}px`,
        flex: 'none'  // 防止单元格被拉伸
      }
    },
    // X号标记样式计算属性
    xMarkStyle() {
      return {
        width: `${this.config.cellWidth * 0.9}px`,
        height: `${this.config.cellHeight * 0.9}px`
      }
    },
    // 是否可以切换到上一贝
    canGoToPreviousBay() {
      return this.bayNumber > 1
    },
    // 是否可以切换到下一贝
    canGoToNextBay() {
      return (this.bayNumber + 2) < (this.bayCount * 2)
    },
    // 当前贝的计划数据
    currentBayPlans() {
      return this.yardPlans.filter(plan => {
        // 检查计划是否包含当前贝号
        const minBay = Math.min(plan.startBay, plan.endBay)
        const maxBay = Math.max(plan.startBay, plan.endBay)
        return this.bayNumber >= minBay && this.bayNumber <= maxBay
      })
    },
    // 当前贝的加锁数据
    currentBayLocks() {
      return this.yardLocks.filter(lock => {
        // 检查加锁是否在当前贝号
        return lock.bay === this.bayNumber
      })
    }
  },
  methods: {
    /**
     * 关闭模态框
     */
    closeModal() {
      this.clearSelection()
      this.$emit('close')
    },
    /**
     * 处理遮罩层点击
     */
    handleOverlayClick() {
      this.closeModal()
    },
    /**
     * 刷新数据
     */
    refreshData() {
      this.$emit('refresh')
    },
    /**
     * 清除选择
     */
    clearSelection() {
      this.selectedCell = { row: null, tier: null }
      this.hoveredCell = { row: null, tier: null }
    },

    /**
     * 判断是否应该显示指定排号
     * @param {number} row - 排号
     * @returns {boolean} 是否显示该排号
     */
    shouldShowRow(row) {
      // 根据配置决定是否间隔显示排号
      if (this.config.intervalDisplayRows) {
        // 间隔显示：只显示奇数排号
        return row % 2 === 1
      } else {
        // 连续显示：显示所有排号
        return true
      }
    },
    /**
     * 判断是否应该显示指定层号
     * @param {number} tier - 层号
     * @returns {boolean} 是否显示该层号
     */
    shouldShowTier(tier) {
      // 根据配置决定是否间隔显示层号
      if (this.config.intervalDisplayTiers) {
        // 间隔显示：只显示奇数层号
        return tier % 2 === 1
      } else {
        // 连续显示：显示所有层号
        return true
      }
    },
    /**
     * 格式化排号显示
     * @param {number} row - 排号
     * @returns {string} 格式化后的排号
     */
    formatRowNumber(row) {
      return row.toString().padStart(2, '0')
    },
    /**
     * 格式化层号显示
     * @param {number} tier - 层号
     * @returns {string} 格式化后的层号
     */
    formatTierNumber(tier) {
      return tier.toString()
    },

    /**
     * 分离集装箱号的字母和数字部分
     * @param {string} containerNo - 集装箱号
     * @returns {Object} 包含字母和数字部分的对象
     */
    splitContainerNo(containerNo) {
      if (!containerNo) return { letters: '', numbers: '' }
      
      // 使用正则表达式分离字母和数字
      const match = containerNo.match(/^([A-Za-z]+)(\d+)$/)
      if (match) {
        return {
          letters: match[1],
          numbers: match[2]
        }
      }
      
      // 如果没有匹配到标准格式，返回原字符串
      return {
        letters: containerNo,
        numbers: ''
      }
    },

    /**
     * 获取指定位置的集装箱
     * @param {number} row - 排号
     * @param {number} tier - 层号
     * @returns {Object|null} 该位置的集装箱对象或null
     */
    getContainerAtPosition(row, tier) {
      // 如果是偶数贝，显示偶数贝的集装箱
      if (this.bayNumber % 2 === 0) {
        return this.bayContainers.find(container => 
          container.row === row && (container.tier || 1) === tier
        ) || null
      } else {
        // 奇数贝，检查是否有偶数贝的集装箱应该显示在这里
        // 偶数贝的箱子显示在前面的奇数贝位置（例如：2贝的箱子显示在1贝的位置）
        const evenBayNumber = this.bayNumber + 1
        const evenBayContainers = this.containerData.filter(container => 
          container.bay === evenBayNumber
        )
        
        // 按位置分组，每个位置只保留一个集装箱（取第一个）
        const positionMap = new Map()
        evenBayContainers.forEach(container => {
          const positionKey = `${container.row}-${container.tier || 1}`
          if (!positionMap.has(positionKey)) {
            positionMap.set(positionKey, container)
          }
        })
        
        const evenBayContainer = Array.from(positionMap.values()).find(container => 
          container.row === row && (container.tier || 1) === tier
        )
        
        if (evenBayContainer) {
          return evenBayContainer
        }
        
        // 如果没有偶数贝集装箱，返回当前贝的集装箱
        return this.bayContainers.find(container => 
          container.row === row && (container.tier || 1) === tier
        ) || null
      }
    },
    /**
     * 获取用于详细信息面板显示的集装箱
     * @param {number} row - 排号
     * @param {number} tier - 层号
     * @returns {Object|null} 该位置的集装箱对象或null
     */
    getDetailContainer(row, tier) {
      // 先尝试获取当前显示位置的集装箱
      const container = this.getContainerAtPosition(row, tier)
      if (container) {
        return container
      }
      
      // 如果当前为奇数贝，且该位置显示X，则应显示前一偶数贝的集装箱信息
      if (this.bayNumber % 2 === 1 && this.shouldShowXMark(row, tier)) {
        const evenBayNumber = this.bayNumber - 1
        const evenBayContainers = this.containerData.filter(container => 
          container.bay === evenBayNumber
        )
        
        // 按位置分组，每个位置只保留一个集装箱（取第一个）
        const positionMap = new Map()
        evenBayContainers.forEach(container => {
          const positionKey = `${container.row}-${container.tier || 1}`
          if (!positionMap.has(positionKey)) {
            positionMap.set(positionKey, container)
          }
        })
        
        return Array.from(positionMap.values()).find(container => 
          container.row === row && (container.tier || 1) === tier
        ) || null
      }
      
      return null
    },
    /**
     * 获取集装箱项样式
     * @param {Object} container - 集装箱对象
     * @returns {Object} 样式对象
     */
    getContainerItemStyle(container) {
      const color = this.getContainerColor(container)
      return {
        width: `${this.config.cellWidth * 0.9}px`,
        height: `${this.config.cellHeight * 0.9}px`,
        backgroundColor: color,
        borderRadius: '6px',
        boxShadow: `
          0 4px 12px rgba(0, 0, 0, 0.15),
          0 2px 6px rgba(0, 0, 0, 0.1),
          inset 0 1px 0 rgba(255, 255, 255, 0.3),
          inset 0 -1px 0 rgba(0, 0, 0, 0.2)
        `,
        position: 'relative',
        overflow: 'hidden'
      }
    },
    /**
     * 获取集装箱颜色
     * @param {Object} container - 集装箱对象
     * @returns {string} 颜色值
     */
    getContainerColor(container) {
      // 直接使用JSON中的color字段，如果没有则使用默认颜色
      return container.color || '#607D8B'
    },
    /**
     * 颜色变暗函数
     * @param {string} color - 十六进制颜色值
     * @param {number} amount - 变暗程度 (0-1)
     * @returns {string} 变暗后的颜色值
     */
    darkenColor(color, amount) {
      const hex = color.replace('#', '')
      const r = Math.max(0, parseInt(hex.substr(0, 2), 16) - Math.round(255 * amount))
      const g = Math.max(0, parseInt(hex.substr(2, 2), 16) - Math.round(255 * amount))
      const b = Math.max(0, parseInt(hex.substr(4, 2), 16) - Math.round(255 * amount))
      return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`
    },
    /**
     * 获取单元格的CSS类名
     * @param {number} row - 排号
     * @param {number} tier - 层号
     * @returns {string} CSS类名字符串
     */
    getCellClass(row, tier) {
      const classes = []
      
      // 检查该单元格是否被选中
      if (this.selectedCell.row === row && this.selectedCell.tier === tier) {
        classes.push('selected')
      }
      
      // 检查该单元格是否被悬停
      if (this.hoveredCell.row === row && this.hoveredCell.tier === tier) {
        classes.push('hovered')
      }
      
      // 检查该单元格是否有X标记
      if (this.shouldShowXMark(row, tier)) {
        classes.push('x-mark-cell')
      }
      
      // 检查该单元格是否在计划范围内
      if (this.getPlanAtPosition(row, tier)) {
        classes.push('plan-cell')
      }
      
      // 检查该单元格是否有加锁
      if (this.getLockAtPosition(row, tier)) {
        classes.push('lock-cell')
      }
      
      return classes.join(' ')
    },
    /**
     * 获取集装箱提示信息
     * @param {Object} container - 集装箱对象
     * @returns {string} 提示信息
     */
    getContainerTooltip(container) {
      return `集装箱: ${container.containerNo}\n类型: ${container.containerType || '20GP'}`
    },
    /**
     * 获取计划覆盖层样式
     * @param {Object} plan - 计划对象
     * @returns {Object} 样式对象
     */
    getPlanOverlayStyle(plan) {
      const color = plan.color || '#2196F3'
      // 解析颜色为RGB值
      const rgb = this.hexToRgb(color)
      
      return {
        width: `${this.config.cellWidth}px`,
        height: `${this.config.cellHeight}px`,
        background: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.05) repeating-linear-gradient(
          45deg,
          transparent,
          transparent 6px,
          rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.2) 6px,
          rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.2) 8px
        )`,
        backgroundSize: '8px 8px',
        position: 'absolute',
        top: '0',
        left: '0',
        zIndex: 5
      }
    },
    /**
     * 获取加锁覆盖层样式
     * @param {Object} lock - 加锁对象
     * @returns {Object} 样式对象
     */
    getLockOverlayStyle(lock) {
      const color = lock.color || '#FF9800'
      // 解析颜色为RGB值
      const rgb = this.hexToRgb(color)
      
      return {
        width: `${this.config.cellWidth}px`,
        height: `${this.config.cellHeight}px`,
        background: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
        borderRadius: '2px',
        position: 'absolute',
        top: '0',
        left: '0',
        zIndex: 6,
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'space-between',
        padding: '2px'
      }
    },
    /**
     * 获取计划提示信息
     * @param {Object} plan - 计划对象
     * @returns {string} 提示信息
     */
    getPlanTooltip(plan) {
      return `计划: ${plan.planId}\n描述: ${plan.description}\n范围: ${plan.startBay}-${plan.endBay}贝 ${plan.startRow}-${plan.endRow}排 ${plan.startTier}-${plan.endTier}层`
    },
    /**
     * 获取加锁提示信息
     * @param {Object} lock - 加锁对象
     * @returns {string} 提示信息
     */
    getLockTooltip(lock) {
      const lockTime = lock.lockTime ? new Date(lock.lockTime).toLocaleString() : '未知时间'
      const lockOperator = lock.lockOperator || '未知操作员'
      const lockReason = lock.lockReason || '未知原因'
      const description = lock.description || '无描述'
      
      return `加锁ID: ${lock.lockId}\n位置: ${lock.bay}贝${lock.row}排\n加锁时间: ${lockTime}\n操作员: ${lockOperator}\n加锁原因: ${lockReason}\n描述: ${description}`
    },
    /**
     * 格式化加锁时间显示
     * @param {string} lockTime - 加锁时间
     * @returns {string} 格式化后的时间 YYYY-MM-DD HH:MM:SS
     */
    formatLockTime(lockTime) {
      if (!lockTime) return '未知时间'
      const date = new Date(lockTime)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      const seconds = date.getSeconds().toString().padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    /**
     * 将十六进制颜色转换为RGB对象
     * @param {string} hex - 十六进制颜色值
     * @returns {Object} RGB对象
     */
    hexToRgb(hex) {
      const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
      return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
      } : { r: 33, g: 150, b: 243 } // 默认蓝色
    },
    /**
     * 检查是否应该显示X号标记
     * @param {number} row - 排号
     * @param {number} tier - 层号
     * @returns {boolean} 是否显示X号标记
     */
    shouldShowXMark(row, tier) {
      // 只有在奇数贝且存在对应的偶数贝集装箱时才显示X号
      // X号显示在后面的奇数贝位置（即当前奇数贝+2的位置）
      if (this.bayNumber % 2 === 1) {
        const evenBayNumber = this.bayNumber - 1
        const evenBayContainers = this.containerData.filter(container => 
          container.bay === evenBayNumber
        )
        
        // 按位置分组，每个位置只保留一个集装箱（取第一个）
        const positionMap = new Map()
        evenBayContainers.forEach(container => {
          const positionKey = `${container.row}-${container.tier || 1}`
          if (!positionMap.has(positionKey)) {
            positionMap.set(positionKey, container)
          }
        })
        
        const evenBayContainer = Array.from(positionMap.values()).find(container => 
          container.row === row && (container.tier || 1) === tier
        )
        
        return !!evenBayContainer
      }
      return false
    },
    /**
     * 检查指定位置是否在计划范围内
     * @param {number} row - 排号
     * @param {number} tier - 层号
     * @returns {Object|null} 包含该位置的计划对象，如果没有则返回null
     */
    getPlanAtPosition(row, tier) {
      return this.currentBayPlans.find(plan => {
        const minRow = Math.min(plan.startRow, plan.endRow)
        const maxRow = Math.max(plan.startRow, plan.endRow)
        const minTier = Math.min(plan.startTier || 1, plan.endTier || 1)
        const maxTier = Math.max(plan.startTier || 1, plan.endTier || 1)
        
        return row >= minRow && row <= maxRow && tier >= minTier && tier <= maxTier
      }) || null
    },
    /**
     * 检查指定位置是否有加锁
     * @param {number} row - 排号
     * @param {number} tier - 层号
     * @returns {Object|null} 包含该位置的加锁对象，如果没有则返回null
     */
    getLockAtPosition(row, tier) {
      return this.currentBayLocks.find(lock => {
        if (lock.row === row && lock.bay === this.bayNumber) {
          // 如果lockTier为null，则该贝所有层都上锁
          if (lock.lockTier === null) {
            return true
          }
          // 如果lockTier有值，则该层及以下都锁（lockTier=1表示第1层不锁，第2层及以上都锁）
          return tier > lock.lockTier
        }
        return false
      }) || null
    },
    /**
     * 单元格点击事件
     * @param {number} row - 排号
     * @param {number} tier - 层号
     */
    onCellClick(row, tier) {
      if (this.selectedCell.row === row && this.selectedCell.tier === tier) {
        this.selectedCell = { row: null, tier: null }
      } else {
        this.selectedCell = { row, tier }
      }
    },
    /**
     * 单元格悬停进入事件
     * @param {number} row - 排号
     * @param {number} tier - 层号
     */
    onCellHover(row, tier) {
      this.hoveredCell = { row, tier }
    },
    /**
     * 单元格悬停离开事件
     */
    onCellLeave() {
      this.hoveredCell = { row: null, tier: null }
    },
    /**
     * 切换到上一贝
     */
    goToPreviousBay() {
      if (this.canGoToPreviousBay) {
        // 贝号只有奇数，所以上一贝是当前贝号减2
        const previousBay = this.bayNumber - 2
        this.$emit('bay-changed', {
          yardId: this.yardId,
          bayNumber: previousBay,
          bayCount: this.bayCount,
          rowCount: this.rowCount,
          tierCount: this.tierCount,
          containerData: this.containerData,
          yardPlans: this.yardPlans,
          yardLocks: this.yardLocks
        })
      }
    },
    /**
     * 切换到下一贝
     */
    goToNextBay() {
      if (this.canGoToNextBay) {
        // 贝号只有奇数，所以下一贝是当前贝号加2
        const nextBay = this.bayNumber + 2
        this.$emit('bay-changed', {
          yardId: this.yardId,
          bayNumber: nextBay,
          bayCount: this.bayCount,
          rowCount: this.rowCount,
          tierCount: this.tierCount,
          containerData: this.containerData,
          yardPlans: this.yardPlans,
          yardLocks: this.yardLocks
        })
      }
    },
  }
}
</script>

<style scoped>
/* 模态框遮罩层 */
.bay-viewer-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 3000;
  animation: fadeIn 0.3s ease-out;
}

/* 模态框主体 */
.bay-viewer-modal {
  background: white;
  border-radius: 6px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  max-width: 90vw;
  max-height: 90vh;
  width: auto;
  height: auto;
  min-width: 800px;
  min-height: 400px;
  display: flex;
  flex-direction: column;
  animation: slideIn 0.3s ease-out;
  overflow: hidden;
}

/* 模态框头部 */
.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e9ecef;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  flex-shrink: 0;
}

.header-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.modal-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.bay-info {
  display: flex;
  gap: 16px;
  font-size: 14px;
  opacity: 0.9;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 24px;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: background-color 0.2s ease;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.close-icon {
  display: block;
  line-height: 1;
}

/* 模态框内容 */
.modal-content {
  flex: 1;
  overflow: auto;
  padding: 16px;
  display: flex;
  gap: 20px;
  min-height: 0;
}

/* 贝图展示区域 */
.bay-view {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.bay-title {
  text-align: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.bay-title h3 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 20px;
  font-weight: 600;
}

.bay-stats {
  display: flex;
  justify-content: center;
  gap: 20px;
  font-size: 14px;
  color: #666;
}

.bay-stats span {
  padding: 4px 8px;
  background: #e9ecef;
  border-radius: 4px;
}

/* 贝图网格样式（参考YardDetail） */
.bay-grid {
  border: 1px solid #333;
  background: #fff;
  width: fit-content;
  min-width: fit-content;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  position: relative;
  z-index: 1;
  overflow: visible;
}

.column-headers {
  display: flex;
  border-bottom: 2px solid #333;
}

/* 通用头部样式 */
.tier-header,
.column-header {
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  padding: 0;
  box-sizing: border-box;
}

.tier-header {
  border-right: 2px solid #333;
}

.column-header {
  border-right: 1px solid #ccc;
}

.column-header:last-child {
  border-right: none;
}

.column-header.empty {
  background-color: #f9f9f9;
}

/* 行样式 */
.bay-row {
  display: flex;
  border-bottom: 1px solid #ccc;
}

.bay-row:last-child {
  border-bottom: none;
}

/* 层号样式 */
.tier-number {
  border-right: 2px solid #333;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  padding: 0;
  font-size: 12px;
  box-sizing: border-box;
}

.tier-number.empty {
  background-color: #f9f9f9;
}

/* 网格单元格样式 */
.grid-cell {
  border-right: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  cursor: pointer;
  overflow: visible;
  background-image:
      radial-gradient(circle at 20% 20%, rgba(255, 255, 255, 0.1) 1px, transparent 1px),
      radial-gradient(circle at 80% 80%, rgba(0, 0, 0, 0.05) 1px, transparent 1px);
  background-size: 8px 8px, 12px 12px;
}


.grid-cell:last-child {
  border-right: none;
}


/* 集装箱项 */
.container-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: white;
  text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.7);
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  transform: scale(1);
  font-family: 'Arial', sans-serif;
  overflow: hidden;
  z-index: 10;
}

.container-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, transparent 50%, rgba(0, 0, 0, 0.1) 100%);
  pointer-events: none;
}

/* 集装箱悬浮效果 */
.container-item:hover {
  transform: scale(1.1);
  z-index: 20;
  filter: brightness(1.15) saturate(1.2) contrast(1.1);
  border-radius: 6px;
  box-shadow:
    0 8px 25px rgba(0, 0, 0, 0.3),
    0 4px 12px rgba(0, 0, 0, 0.2),
    0 0 0 3px rgba(74, 144, 226, 0.8),
    0 0 20px rgba(74, 144, 226, 0.5),
    0 0 40px rgba(74, 144, 226, 0.3);
  transition: all 0.2s ease;
}

/* 集装箱选中样式 */
.container-item.container-selected {
  transform: scale(1);
  z-index: 15;
  filter: brightness(1.1) saturate(1.15) contrast(1.05);
  border-radius: 6px;
  box-shadow:
    0 6px 20px rgba(0, 0, 0, 0.25),
    0 3px 10px rgba(0, 0, 0, 0.15),
    0 0 0 5px rgba(40, 167, 69, 0.9),
    0 0 15px rgba(40, 167, 69, 0.4),
    0 0 30px rgba(40, 167, 69, 0.2);
  animation: containerSelectedPulse 2s ease-in-out infinite;
}

/* 集装箱选中动画 */
@keyframes containerSelectedPulse {
  0%, 100% {
    box-shadow:
      0 6px 20px rgba(0, 0, 0, 0.25),
      0 3px 10px rgba(0, 0, 0, 0.15),
      0 0 0 5px rgba(40, 167, 69, 0.9),
      0 0 15px rgba(40, 167, 69, 0.4),
      0 0 30px rgba(40, 167, 69, 0.2);
  }
  50% {
    box-shadow:
      0 8px 25px rgba(0, 0, 0, 0.3),
      0 4px 12px rgba(0, 0, 0, 0.2),
      0 0 0 6px rgba(40, 167, 69, 1),
      0 0 20px rgba(40, 167, 69, 0.6),
      0 0 40px rgba(40, 167, 69, 0.3);
  }
}

.container-no {
  margin-bottom: 3px;
  text-align: left;
  line-height: 1.1;
  text-transform: uppercase;
  color: white;
}

.container-letters {
  font-size: 12px;
  font-weight: 700;
  letter-spacing: 0.5px;
  color: white;
  text-align: left;
}

.container-numbers {
  font-size: 10px;
  font-weight: 600;
  letter-spacing: 0.3px;
  color: white;
  text-align: left;
}

.container-type {
  font-size: 9px;
  text-align: left;
  line-height: 1;
  font-weight: 600;
  letter-spacing: 0.3px;
  color: white;
}

/* X号标记样式 */
.x-mark {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 10;
  pointer-events: none;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* X号对角线样式 */
.x-line {
  position: absolute;
  background-color: #dc3545;
  box-shadow: 0 0 4px rgba(220, 53, 69, 0.6);
}

.x-line-1 {
  top: 50%;
  left: 50%;
  width: 100%;
  height: 3px;
  transform: translate(-50%, -50%) rotate(45deg);
  transform-origin: center;
}

.x-line-2 {
  top: 50%;
  left: 50%;
  width: 100%;
  height: 3px;
  transform: translate(-50%, -50%) rotate(-45deg);
  transform-origin: center;
}

/* X号标记悬浮效果 */
.x-mark.x-mark-hovered {
  transform: translate(-50%, -50%) scale(1.1);
  z-index: 20;
  border-radius: 6px;
  filter: brightness(1.15) saturate(1.2) contrast(1.1);
  box-shadow:
    0 8px 25px rgba(220, 53, 69, 0.3),
    0 4px 12px rgba(220, 53, 69, 0.2),
    0 0 0 3px rgba(220, 53, 69, 0.8),
    0 0 20px rgba(220, 53, 69, 0.5),
    0 0 40px rgba(220, 53, 69, 0.3);
  transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

/* X号标记选中效果 */
.x-mark.x-mark-selected {
  transform: translate(-50%, -50%) scale(1);
  z-index: 15;
  border-radius: 6px;
  filter: brightness(1.1) saturate(1.15) contrast(1.05);
  box-shadow:
    0 6px 20px rgba(220, 53, 69, 0.25),
    0 3px 10px rgba(220, 53, 69, 0.15),
    0 0 0 5px rgba(220, 53, 69, 0.9),
    0 0 15px rgba(220, 53, 69, 0.4),
    0 0 30px rgba(220, 53, 69, 0.2);
  transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  animation: xMarkSelectedPulse 2s ease-in-out infinite;
}

/* X号标记选中动画 */
@keyframes xMarkSelectedPulse {
  0%, 100% {
    box-shadow:
      0 6px 20px rgba(220, 53, 69, 0.25),
      0 3px 10px rgba(220, 53, 69, 0.15),
      0 0 0 5px rgba(220, 53, 69, 0.9),
      0 0 15px rgba(220, 53, 69, 0.4),
      0 0 30px rgba(220, 53, 69, 0.2);
  }
  50% {
    box-shadow:
      0 8px 25px rgba(220, 53, 69, 0.3),
      0 4px 12px rgba(220, 53, 69, 0.2),
      0 0 0 6px rgba(220, 53, 69, 1),
      0 0 20px rgba(220, 53, 69, 0.6),
      0 0 40px rgba(220, 53, 69, 0.3);
  }
}

/* 计划覆盖层样式 */
.plan-overlay {
  pointer-events: none;
}

/* 加锁覆盖层样式 */
.lock-overlay {
  pointer-events: none;
}

.lock-overlay .lock-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  font-size: 10px;
  line-height: 1.2;
  color: #333;
  text-shadow: 0 1px 2px rgba(255, 255, 255, 0.8);
}

.lock-overlay .lock-id {
  font-weight: bold;
  color: #FF9800;
  font-size: 9px;
}

.lock-overlay .lock-time {
  font-weight: bold;
  color: #666;
}

.lock-overlay .lock-reason {
  color: #333;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.lock-overlay .lock-icon {
  font-size: 14px;
  color: rgba(255, 152, 0, 0.8);
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  align-self: flex-end;
  margin-top: auto;
}

/* 加锁单元格样式 */
.lock-cell {
  background-color: rgba(255, 152, 0, 0.05) !important;
}


/* 详细信息面板 */
.detail-panel {
  width: 240px;
  min-width: 240px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  padding: 16px;
  max-height: 100%;
  overflow-y: auto;
  flex-shrink: 0;
}

.detail-panel h4 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 1px solid #dee2e6;
  padding-bottom: 8px;
}

.container-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.container-detail-item {
  background: white;
  border-radius: 6px;
  border: 1px solid #dee2e6;
  padding: 12px;
  transition: box-shadow 0.2s ease;
}

.container-detail-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.tier-badge {
  background: #007bff;
  color: white;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 10px;
  font-weight: bold;
}

.container-no {
  font-weight: bold;
  color: #333;
  font-size: 14px;
}

.detail-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
}

.info-row .label {
  color: #666;
  font-weight: 500;
}

.info-row .value {
  color: #333;
  font-weight: 600;
}

/* 空位置信息 */
.empty-position {
  margin-top: 16px;
}

.empty-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px dashed #dee2e6;
}

.empty-icon {
  font-size: 24px;
  opacity: 0.5;
}

.empty-text {
  color: #666;
  font-size: 14px;
  font-style: italic;
}

/* 模态框底部 */
.modal-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  padding: 8px 12px;
  border-top: 1px solid #e9ecef;
  background: #f8f9fa;
  flex-shrink: 0;
}

/* 贝号导航区域 */
.bay-navigation {
  display: flex;
  gap: 8px;
  align-items: center;
}

/* 右侧操作按钮区域 */
.footer-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 12px;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #5a6268;
}

.btn-primary {
  background: #3498db;
  color: white;
}

.btn-primary:hover {
  background: #2980b9;
}

.btn-warning {
  background: #f39c12;
  color: white;
}

.btn-warning:hover {
  background: #e67e22;
}

/* 导航按钮样式 */
.btn-nav {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 10px;
  font-size: 12px;
  font-weight: 500;
  background: #6c757d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 80px;
  justify-content: center;
}

.btn-nav:hover:not(:disabled) {
  background: #5a6268;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.btn-nav:disabled {
  background: #adb5bd;
  color: #6c757d;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.btn-nav .nav-icon {
  font-size: 16px;
  font-weight: bold;
  line-height: 1;
}

.btn-nav .nav-text {
  font-size: 12px;
  font-weight: 500;
}

/* 上一贝按钮特殊样式 */
.btn-prev {
  background: #495057;
}

.btn-prev:hover:not(:disabled) {
  background: #343a40;
}

/* 下一贝按钮特殊样式 */
.btn-next {
  background: #495057;
}

.btn-next:hover:not(:disabled) {
  background: #343a40;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: scale(0.9) translateY(-20px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}


/* 响应式设计 */
@media (max-width: 768px) {
  .bay-viewer-modal {
    max-width: 95vw;
    max-height: 95vh;
    min-width: 400px;
    min-height: 300px;
  }

  .modal-content {
    flex-direction: column;
    gap: 16px;
  }

  .detail-panel {
    width: 100%;
    max-height: 200px;
  }

  .bay-info {
    flex-direction: column;
    gap: 4px;
  }

  /* 响应式导航按钮 */
  .modal-footer {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .bay-navigation {
    justify-content: center;
    order: 2;
  }

  .footer-actions {
    justify-content: center;
    order: 1;
  }

  .btn-nav {
    min-width: 70px;
    padding: 5px 8px;
    font-size: 11px;
  }

  .btn-nav .nav-text {
    font-size: 11px;
  }

  .btn-nav .nav-icon {
    font-size: 14px;
  }
}
</style>
